<template>
  <div class="login-page">
    <div class="header">
      <img src="@/assets/logo.png">
      <h1 class="title">团多多</h1>
    </div>

    <!-- 登录标签页 -->
    <van-tabs v-model:active="activeTab" class="login-tabs" animated>
      <!-- 密码登录标签 -->
      <van-tab title="账号登录">
        <div class="login-form">
          <van-cell-group inset>
            <van-field v-model="loginType.phone" label="账号" placeholder="手机号" />
            <van-field v-model="loginType.password" type="password" label="密码" placeholder="密码" />
            <!-- 图形验证码 -->
            <van-field v-model="loginType.code" label="验证码" placeholder="图形验证码">
              <template #button>
                <div class="captcha-container">
                  <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" @click="refreshCaptcha" class="captcha-image" />
                </div>
              </template>
            </van-field>
          </van-cell-group>
        </div>
      </van-tab>

      <!-- 邮箱验证码登录标签 -->
      <van-tab title="邮箱登录">
        <div class="login-form">
          <van-cell-group inset>
            <van-field v-model="loginType.email" label="邮箱" placeholder="邮箱" />
            <van-field v-model="loginType.emailCode" label="验证码" placeholder="邮箱验证码" class="email-align">
              <template #button>
                <van-button size="small" type="primary" :disabled="codeButtonDisabled" @click="sendEmailCode">
                  {{ codeButtonText }}
                </van-button>
              </template>
            </van-field>
            <!-- 图形验证码 -->
            <van-field v-model="loginType.code" label="图形验证码" placeholder="图形验证码">
              <template #button>
                <div class="captcha-container">
                  <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" @click="refreshCaptcha" class="captcha-image" />
                </div>
              </template>
            </van-field>
          </van-cell-group>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 共用登录按钮 -->
    <div class="submit-button">
      <van-button round block type="primary" @click="onLogin()" color="#f40">
        登录
      </van-button>
    </div>

    <!-- 注册链接 -->
    <div class="register-link">
      <span class="register-text">还没有账号？</span>
      <span class="register-action" @click="goToRegister()">立即注册</span>
    </div>

    <!-- 协议说明 -->
    <div class="agreement">
      <van-checkbox v-model="agreed" checked-color="#f40">
        <span class="agreement-text">
          我已阅读并同意 <span class="link">用户协议</span> 和 <span class="link">隐私政策</span>
        </span>
      </van-checkbox>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onUnmounted, onMounted } from 'vue'
import { showLoadingToast, showToast } from 'vant'
import { useRouter } from 'vue-router'
import type { LoginType, CheckCodeType } from '@/models/login/index'
import { getcheckCode, getEmailCode, login } from '@/api/login'

// 路由
const router = useRouter()
// 标签页控制
const activeTab = ref(0)

// 邮箱验证正则
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
// 手机号验证正则
const phonePattern = /^1[3456789]\d{9}$/

// 密码登录表单数据
const loginType = reactive<LoginType>({
  email: '', // 邮箱
  phone: '', // 手机号
  password: '', // 密码
  code: '',// 图形验证码
  emailCode: '', // 邮箱验证码
  loginType: 0,
  checkCodeKey: ''
})

const checkCode = reactive<CheckCodeType>({
  email: '',
  checkCode: '',
  checkCodeKey: ''
})


// 验证码倒计时相关
const codeCountdown = ref(0)
const codeTimer = ref<number | null>(null)

// 协议同意状态
const agreed = ref(false)

// 图形验证码相关
const captchaUrl = ref<string>('')

// 计算属性：验证码按钮状态
const codeButtonDisabled = computed(() => {
  return codeCountdown.value > 0 || !emailPattern.test(loginType.email)
})

// 计算属性：验证码按钮文字
const codeButtonText = computed(() => {
  if (codeCountdown.value > 0) {
    return `${codeCountdown.value}秒后重发`
  }
  return '发送验证码'
})

// 获取图形验证码
const fetchCaptcha = async () => {
  // 这里应该替换为实际的API地址
  // 示例使用一个占位图片，实际项目中需要调用后端接口获取验证码
  const res = (await getcheckCode()).data
  console.log('res:', res);

  captchaUrl.value = res.checkCode
  checkCode.checkCodeKey = res.checkCodeKey
}

// 刷新图形验证码
const refreshCaptcha = () => {
  fetchCaptcha()
}

// 发送邮箱验证码
const sendEmailCode = () => {
  if (!loginType.code) {
    showToast({ message: '请先输入图形验证码', type: 'fail' })
    return
  }

  if (!emailPattern.test(loginType.email)) {
    showToast({ message: '请输入正确的邮箱格式', type: 'fail' })
    return
  }

  showToast({ message: '发送中...', type: 'loading' })
  setTimeout(() => {
    showToast({ message: '验证码已发送', type: 'success' })
    checkCode.email = loginType.email
    checkCode.checkCode = loginType.code
    getEmailCode(checkCode)
    // 启动倒计时
    codeCountdown.value = 60
    codeTimer.value = window.setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0 && codeTimer.value) {
        clearInterval(codeTimer.value)
      }
    }, 1000)
  }, 1000)
}

// 根据当前标签页执行对应的登录逻辑
const onLogin = async () => {
  loginType.loginType = activeTab.value;
  let isValid = false;
  if (activeTab.value === 0) {
    isValid = onPasswordLogin()

  } else {
    isValid = onEmailCodeLogin()
  }

  // 如果验证失败，直接返回，不执行登录请求
  if (!isValid) {
    return;
  }

  loginType.checkCodeKey = checkCode.checkCodeKey

  showToast({ message: '正在登录...', type: 'loading' })
  // 使用正确的类型
  const res = await login(loginType)

  showToast("登录成功, 正在跳转...")


  localStorage.setItem("token", res.data.token)
  localStorage.setItem("userInfo", JSON.stringify(res.data))
  setTimeout(() => {
    router.push('/main')
  }, 1000)

}

// 密码登录处理
const onPasswordLogin = () => {
  if (!agreed.value) {
    showToast({ message: '请先同意用户协议和隐私政策', type: 'fail' })
    return false
  }
  // 添加手机号验证
  if (!phonePattern.test(loginType.phone)) {
    showToast({ message: '请输入正确的手机号', type: 'fail' })
    return false
  }

  // 添加图形验证码验证
  if (!loginType.code) {
    showToast({ message: '请输入图形验证码', type: 'fail' })
    return false
  }
  if (!loginType.password) {
    showToast({ message: '请输入密码', type: 'fail' })
    return false
  }
  return true
}

// 邮箱验证码登录处理
const onEmailCodeLogin = () => {
  if (!agreed.value) {
    showToast({ message: '请先同意用户协议和隐私政策', type: 'fail' })
    return false
  }
  if (!emailPattern.test(loginType.email)) {
    showToast({ message: '请输入正确的邮箱', type: 'fail' })
    return false
  }
  if (loginType.email == '') {
    showToast({ message: '请输入邮箱', type: 'fail' })
    return false
  }
  if (!loginType.code) {
    showToast({ message: '请输入验证码', type: 'fail' })
    return false
  }
  return true
}

const goToRegister = () => {
  // 跳转到注册页
  console.log('跳转到注册页')
  router.push('/register')
}

// 组件销毁时清理定时器
onUnmounted(() => {
  if (codeTimer.value) {
    clearInterval(codeTimer.value)
  }
})

// 组件挂载时获取验证码
onMounted(() => {
  fetchCaptcha()
  // deleteCookie('token');
})


function deleteCookie(name: any) {

  document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';

}
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  background: #ffffff;
  padding-bottom: 40px;
}

.header {
  padding: 40px 20px 20px;
  text-align: center;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 14px;
  color: #666;
}

.login-tabs {
  height: 210px;
  margin-top: 20px;
}

:deep(.van-tabs__nav) {
  background: transparent;
}

:deep(.van-tab--active) {
  color: #f40;
}

:deep(.van-tabs__line) {
  background-color: #f40;
}

.login-form {
  padding: 20px 0;
}

.submit-button {
  margin: 30px 15px 0;
}

.register-link {
  text-align: center;
  margin: 20px 0;
}

.register-text {
  font-size: 14px;
  color: #666;
}

.register-action {
  font-size: 14px;
  color: #f40;
  margin-left: 5px;
  cursor: pointer;
}

.agreement {
  padding: 20px 15px 0;
}

.agreement-text {
  font-size: 12px;
  color: #666;
}

.link {
  color: #f40;
}

.captcha-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
}

.captcha-image {
  height: 25px;
  cursor: pointer;
  margin-left: 10px;
}

:deep(.van-cell-group) {
  .van-cell {
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.email-align {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
}
</style>